package com.zkjd.lingdong.ui.home

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.absolutePadding
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Help
import androidx.compose.material.icons.automirrored.filled.MenuOpen
import androidx.compose.material.icons.filled.Create
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import androidx.compose.ui.window.PopupProperties
import androidx.core.graphics.drawable.toBitmap
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavController
import com.adayo.service.utils.CarPropertyUtils
import com.adayo.service.utils.DriveModelManager
import com.adayo.service.utils.VirtualCarUtils
import com.mega.nexus.os.MegaSystemProperties
import com.wt.offline.CarFeature
import com.wt.offline.utils.OfflineConfig
import com.zkjd.lingdong.R
import com.zkjd.lingdong.bluetooth.BleAuthUtils
import com.zkjd.lingdong.data.FunctionsConfig
import com.zkjd.lingdong.model.ButtonFunction
import com.zkjd.lingdong.model.Device
import com.zkjd.lingdong.model.FunctionCategory
import com.zkjd.lingdong.ui.function.FunctionIcon
import com.zkjd.lingdong.ui.theme.BorderColor
import com.zkjd.lingdong.ui.theme.CardBackground
import com.zkjd.lingdong.ui.theme.DarkBackground
import com.zkjd.lingdong.ui.theme.Error
import com.zkjd.lingdong.ui.theme.Primary
import com.zkjd.lingdong.ui.theme.Success
import com.zkjd.lingdong.ui.theme.Warning

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
    navController: NavController,
    viewModel: HomeViewModel,
) {
    // 获取功能配置实例
    val functionsConfig = remember { FunctionsConfig.getInstance(viewModel.getContext()) }
    val context = LocalContext.current
    val devices by viewModel.devices.collectAsState(initial = emptyList())
    val useMeijiaCar by viewModel.useMeijiaCar.collectAsState()
    val useCarAudio by viewModel.useCarAudio.collectAsState()
    val enableAuthentication by viewModel.enableAuthentication.collectAsState()
    val initialSetup by viewModel.initialSetup.collectAsState()
    val useMusic by viewModel.useMusic.collectAsState()
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    var toast: Toast? = null
    var showSetting by remember { mutableStateOf(true) }
    var showBattleLowDialog by remember { mutableStateOf(false) }
    var deviceName: String?=""

    val useMusicTypeName by viewModel.useMusicTypeName.collectAsState()
    //首次设置判断
    if (!initialSetup){
        showSetting=true
    }else
    {
        showSetting=false
    }


    var testString: String="读不到"

    var showTestDialog by remember { mutableStateOf(false) }

    LaunchedEffect(key1 = true) {
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.uiEvents.collect { event ->
                when (event) {
                    is HomeViewModel.UiEvent.ShowToast -> {
                        if(toast==null) {
                            toast = Toast.makeText(context, event.message, Toast.LENGTH_SHORT)
                        }else{
                            //有新的消息即时更新，不用等待上一个消息显示完成以后再显示，造成延时很长的感觉
                            toast?.setText(event.message)
                        }
                        toast?.show()
                    }

                    is HomeViewModel.UiEvent.Navigate -> {
                        deviceName=event.route
                        showBattleLowDialog=true
                    }

                    else -> {}
                }
            }
        }
    }
    Scaffold(
        topBar = {
            TopAppBar(
                title = {},
                actions = {
                    TextButton(
                        onClick = {
                            // 打开购买与帮助网页
                            showSetting=true
                        }
                    ) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.MenuOpen,
                            contentDescription = "设置",
                            tint = Color.White,
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "设置",
                            color = Color.White,
                            fontSize = 14.sp
                        )
                    }
                    Spacer(Modifier.width(10.dp))
//                    TextButton(
//                        onClick = {
//                            // 打开购买与帮助网页
//                            val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com"))
//                            context.startActivity(intent)
//                        }
//                    ) {
//                        Icon(
//                            imageVector = Icons.AutoMirrored.Filled.Help,
//                            contentDescription = "帮助",
//                            tint = Color.White,
//                            modifier = Modifier.size(18.dp)
//                        )
//                        Spacer(modifier = Modifier.width(4.dp))
//                        Text(
//                            text = "购买与帮助",
//                            color = Color.White,
//                            fontSize = 14.sp
//                        )
//                    }

                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = DarkBackground
                )
            )
        },
        containerColor = DarkBackground
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .padding(paddingValues)
                .fillMaxSize()
        ) {
//横向展示
//            LazyRow(
//                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 0.dp),
//                horizontalArrangement = Arrangement.spacedBy(16.dp),
//                modifier = Modifier.fillMaxWidth()
//            ) {
            //9宫格展示
            LazyVerticalGrid(
                columns = GridCells.Fixed(3),
                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
                horizontalArrangement = Arrangement.spacedBy(25.dp),
                verticalArrangement = Arrangement.spacedBy(25.dp)
            ) {
                items(devices) { device ->
                    DeviceCard(device, viewModel, navController)
                }

                // 添加设备卡片
                item {
                    AddDeviceCard {
                        // 跳转到配对界面
                        navController.navigate("pairing")
                    }
                }
            }

            SettingDialog2(
                functionsConfig=functionsConfig,
                viewModel=viewModel,
                enableAuthentication=useMusic,
                useMusic = useMusicTypeName,
                showSetting=showSetting,
                onDismissRequest = {
                    showSetting=false
                    viewModel.toInitialSetupExecutor()
                }
            )

            // 电量低弹窗
            if (showBattleLowDialog) {
                BatteryDeviceDialog(
                    currentName = deviceName+"妥妥贴电池电量已过低，请及时更换电池！",
                    onDismiss = { showBattleLowDialog = false },
                    onConfirm = { newName ->
                        showBattleLowDialog = false
                    }
                )
            }
//            // 底部切换按钮区域
//            Card(
//                modifier = Modifier
//                    .fillMaxWidth()
//                    .padding(2.dp)
//                    .align(Alignment.BottomCenter)
//            ) {
//                Row(
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .padding(vertical = 2.dp),
//                    horizontalArrangement = Arrangement.SpaceAround,
//                    verticalAlignment = Alignment.CenterVertically
//                ) {
//                    Switch(
//                        checked = useMeijiaCar,
//                        onCheckedChange = { viewModel.toggleCarExecutor() }
//                    )
//                    Text(
//                        text = "镁佳Car",
//                        style = MaterialTheme.typography.bodyLarge
//                    )
//
//                    Switch(
//                        checked = useCarAudio,
//                        onCheckedChange = { viewModel.toggleCarAudio() }
//                    )
//                    Text(
//                        text = "CarAudio",
//                        style = MaterialTheme.typography.bodyLarge
//                    )
//
//                    Switch(
//                        checked = enableAuthentication,
//                        onCheckedChange = { viewModel.toggleAuthentication() }
//                    )
//                    Text(
//                        text = "设备鉴权",
//                        style = MaterialTheme.typography.bodyLarge
//                    )
//                }
//            }
        }

        //梧桐配置字

//        var testfx=""
//        var testzjjr=""
//        var test1=""
//        var test2=""
//        var test3=""
//        var test4=""
//        var test5=""
//        var test6=""
//        OfflineConfig.getInstance().registerListener {
//            //服务已加载完成，可以读取配置
//            testString = OfflineConfig.getInstance().getValue("car_feature_back_door_type").toString()
//            testfx = OfflineConfig.getInstance().getValue("car_feature_vehicle_type").toString()
//            testzjjr = OfflineConfig.getInstance().getValue(CarFeature.FEATURE_CAR_MD_SEAT_HEATING).toString()
//            test1 = OfflineConfig.getInstance().getValue(CarFeature.FEATURE_CAR_CO_SEAT_HEATING).toString()
//            test2 = OfflineConfig.getInstance().getValue(CarFeature.FEATURE_CAR_MD_SEAT_VENTILATION).toString()
//            test3 = OfflineConfig.getInstance().getValue(CarFeature.FEATURE_CAR_CO_SEAT_VENTILATION).toString()
//            test4 = OfflineConfig.getInstance().getValue(CarFeature.FEATURE_ELECTRIC_TAIL_WINGS).toString()
//            test5 = OfflineConfig.getInstance().getValue(CarFeature.FEATURE_REARVIEW_MIRROR_FOLD).toString()
//            test6 = OfflineConfig.getInstance().getValue(CarFeature.FEATURE_PASSENGER_SEAT_ADJUSTMENT).toString()
//        }

//        if(byte!=null) {
//            testString = BleAuthUtils.byteArrayToHexString(byte)
//        }else{
//            testString="读不到，或者读出来是错误的"
//        }


        //测试配置字是否可获取
//        val intString = DriveModelManager.getModels(DriveModelManager.ELECTRIC_TAILGATE)
//        val intString2=DriveModelManager.getModels(DriveModelManager.POWER_MODE)
//
//        testString="后尾箱开关："+intString.toString()+"能量管理模式："+intString2

//        var model = MegaSystemProperties.getInt(DriveModelManager.PROP_ECU_CONFIG_C385_VEHICLE_TYPE, 0);
//        var model2 = MegaSystemProperties.getInt(DriveModelManager.PROP_ECU_CONFIG_SUB_VEHICLEMODEL, 0);
//
//        testString="子车型："+model2.toString()+"主车型："+model.toString()
//        showTestDialog=true
        // 测试
//        if (showTestDialog) {
//            TestDialog(
//                //stringMaessage="后尾开关："+testString+"能量模式："+testfx+"主座加热："+testzjjr+"副座加热："+test1+"主座通风："+test2+"副座通风："+test3+"尾翼档位："+test4+"后视镜折叠："+test5+"老板键："+test6,
//                stringMaessage=testString,
//                onDismiss = {
//                    showTestDialog = false
//                },
//                onConfirm = {
//                    showTestDialog = false
//                    navController.popBackStack()
//                }
//            )
//        }

    }
}

@Composable
fun DeviceCard(
    device: Device,
    viewModel: HomeViewModel,
    navController: NavController,
    modifier: Modifier = Modifier,
) {
    var showMenu by remember { mutableStateOf(false) }
    var showRenameDialog by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    // 存储按钮位置信息，以便弹出菜单
    var menuButtonPosition by remember { mutableStateOf(Offset.Zero) }

    Card(
        modifier = modifier
            .defaultMinSize(minWidth = 160.dp)
            .width(IntrinsicSize.Max)//动态宽度调整
            .height(220.dp)
            .clickable(onClick = {  navController.navigate("function/${device.macAddress}") }),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = CardBackground
        ),
        border = BorderStroke(1.dp, BorderColor)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp)
        ) {
            // 顶部栏 - 电量和编辑按钮
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 电量指示器 - 横向进度条样式
                BatteryIndicator(batteryLevel = device.batteryLevel ?: 80)

                //Spacer(modifier = Modifier.weight(1f)) // 占据剩余空间

                // 编辑按钮
                IconButton(
                    onClick = { showMenu = true },
                    modifier = Modifier
                        .size(22.dp)
                        .onGloballyPositioned { coordinates ->
                            // 获取按钮在屏幕上的位置
                            menuButtonPosition = coordinates.positionInWindow()
                        }
                ) {
                    Icon(
                        imageVector = Icons.Default.Create,
                        contentDescription = "编辑",
                        tint = Color.White
                    )
                }

                // 自定义弹出菜单
                if (showMenu) {
                    Popup(
                        onDismissRequest = { showMenu = false },
                        properties = PopupProperties(focusable = true),
                        popupPositionProvider = object : PopupPositionProvider {
                            override fun calculatePosition(
                                anchorBounds: IntRect,
                                windowSize: IntSize,
                                layoutDirection: LayoutDirection,
                                popupContentSize: IntSize
                            ): IntOffset {
                                return IntOffset(
                                    x = anchorBounds.left + anchorBounds.width-450, // 右侧
                                    y = anchorBounds.top // 与顶部对齐
                                )
                            }
                        }
                    ) {
                        val widthPixels = LocalContext.current.resources.displayMetrics.widthPixels
                        val targetDensity = widthPixels / 1060f
                        CompositionLocalProvider(LocalDensity provides Density(density = targetDensity)) {

                            Card(
                                modifier = Modifier
                                    .width(180.dp)
                                    .shadow(8.dp, RoundedCornerShape(12.dp))
                                    .clip(RoundedCornerShape(12.dp)),
                                colors = CardDefaults.cardColors(
                                    containerColor = Color(0xFF3C3C48)
                                )
                            ) {
                                Column(
                                    modifier = Modifier.padding(8.dp)
                                ) {
//                                    CustomMenuItem(
//                                        text = "按键设置",
//                                        onClick = {
//                                            showMenu = false
//                                            navController.navigate("function/${device.macAddress}")
//                                        }
//                                    )

                                    CustomMenuItem(
                                        text = "颜色设置",
                                        onClick = {
                                            showMenu = false
                                            navController.navigate("led_color/${device.macAddress}")
                                        }
                                    )

                                    CustomMenuItem(
                                        text = "重命名",
                                        onClick = {
                                            showMenu = false
                                            showRenameDialog = true
                                        }
                                    )

                                    CustomMenuItem(
                                        text = "删除",
                                        onClick = {
                                            showMenu = false
                                            showDeleteDialog = true
                                        },
                                        isDestructive = true
                                    )
                                }
                            }
                        }
                    }
                }
            }


            // 设备内容区域
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .padding(vertical = 2.dp),
                contentAlignment = Alignment.Center
            ) {
                // 检查设备是否有设置按键功能
                val hasFunctions = device.shortPressFunction != null ||
                        //device.longPressFunction != null ||
                        device.doubleClickFunction != null ||
                        device.leftRotateFunction != null;
                        //device.rightRotateFunction != null

                if (!hasFunctions) {
                    // 显示默认设备图标
                    DeviceIcon()
                } else {
                    // 显示设备功能
                    DeviceFunctions(device)
                }
            }

            // 设备名称
            Text(
                text = device.name,
                color = Color.White,
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                modifier = Modifier.align(Alignment.CenterHorizontally)
            )
        }
    }

    // 重命名对话框
    if (showRenameDialog) {
        RenameDeviceDialog(
            currentName = device.name,
            onDismiss = { showRenameDialog = false },
            onConfirm = { newName ->
                viewModel.renameDevice(device.macAddress, newName)
                showRenameDialog = false
            }
        )
    }

    // 删除确认对话框
    if (showDeleteDialog) {
        ConfirmDeleteDialog(
            deviceName = device.name,
            onDismiss = { showDeleteDialog = false },
            onConfirm = {
                viewModel.deleteDevice(device)
                showDeleteDialog = false
            }
        )
    }

}

@Composable
fun BatteryIndicator(batteryLevel: Int) {
    val batteryWidth = 36.dp
    val batteryHeight = 16.dp

    Box(
        modifier = Modifier
            .width(batteryWidth)
            .height(batteryHeight)
            .background(Color.Transparent)
    ) {
        // 电池外框
        Box(
            modifier = Modifier
                .fillMaxSize()
                .border(1.dp, Color.White, RoundedCornerShape(4.dp))
        )

        // 电池电量填充
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .width(batteryWidth * batteryLevel / 100)
                .padding(2.dp)
                .background(getBatteryColor(batteryLevel), RoundedCornerShape(2.dp))
        )

        // 电池正极头
        Box(
            modifier = Modifier
                .width(2.dp)
                .height(8.dp)
                .background(Color.White)
                .align(Alignment.CenterEnd)
                .offset(x = 2.dp)
        )
    }
}

@Composable
fun CustomMenuItem(
    text: String,
    onClick: () -> Unit,
    isDestructive: Boolean = false
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 12.dp, horizontal = 16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {

        Text(
            text = text,
            color = if (isDestructive) Error else Color.White,
            fontSize = 14.sp
        )
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RenameDeviceDialog(
    currentName: String,
    onDismiss: () -> Unit,
    onConfirm: (String) -> Unit
) {
    var name by remember { mutableStateOf(currentName) }

    Dialog(onDismissRequest = onDismiss) {
        val widthPixels = LocalContext.current.resources.displayMetrics.widthPixels
        val targetDensity = widthPixels / 1060f
        CompositionLocalProvider(LocalDensity provides Density(density = targetDensity)) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = CardBackground
            ) {
                Column(
                    modifier = Modifier
                        .padding(24.dp)
                        .width(300.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "重命名设备",
                        color = Color.White,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )

                    Spacer(modifier = Modifier.height(16.dp))

                    OutlinedTextField(
                        value = name,
                        onValueChange = { name = it },
                        label = { Text("设备名称") },
                        singleLine = true,
                        modifier = Modifier.fillMaxWidth()
                    )

                    Spacer(modifier = Modifier.height(24.dp))

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End
                    ) {
                        TextButton(onClick = onDismiss) {
                            Text("取消", color = Color.White)
                        }

                        TextButton(
                            onClick = { onConfirm(name) },
                            enabled = name.isNotBlank()
                        ) {
                            Text("确定", color = Primary)
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun BatteryDeviceDialog(
    currentName: String,
    onDismiss: () -> Unit,
    onConfirm: (String) -> Unit
) {
    var name by remember { mutableStateOf(currentName) }

    Dialog(onDismissRequest = onDismiss) {
        val widthPixels = LocalContext.current.resources.displayMetrics.widthPixels
        val targetDensity = widthPixels / 1060f
        CompositionLocalProvider(LocalDensity provides Density(density = targetDensity)) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = CardBackground
            ) {
                Column(
                    modifier = Modifier
                        .padding(24.dp)
                        .width(300.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "温馨提示",
                        color = Color.White,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )

                    Spacer(modifier = Modifier.height(16.dp))

                    Text(
                        text = name,
                        color = Color.White
                    )

                    Spacer(modifier = Modifier.height(24.dp))

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End
                    ) {
                        TextButton(
                            onClick = { onConfirm(name) },
                            enabled = name.isNotBlank()
                        ) {
                            Text("确定", color = Primary)
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun ConfirmDeleteDialog(
    deviceName: String,
    onDismiss: () -> Unit,
    onConfirm: () -> Unit
) {

    Dialog(onDismissRequest = onDismiss) {
        val widthPixels = LocalContext.current.resources.displayMetrics.widthPixels
        val targetDensity = widthPixels / 1060f
        CompositionLocalProvider(LocalDensity provides Density(density = targetDensity)) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = CardBackground
            ) {
                Column(
                    modifier = Modifier
                        .padding(24.dp)
                        .width(300.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "删除设备",
                        color = Color.White,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )

                    Spacer(modifier = Modifier.height(16.dp))

                    Text(
                        text = "确定要删除设备" +   deviceName + "吗？此操作不可恢复。",
                        color = Color.White
                    )

                    Spacer(modifier = Modifier.height(24.dp))

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End
                    ) {
                        TextButton(onClick = onDismiss) {
                            Text("取消", color = Color.White)
                        }

                        TextButton(onClick = onConfirm) {
                            Text("确定删除", color = Error)
                        }
                    }
                }
            }
        }
    }


//    AlertDialog(
//
//        onDismissRequest = onDismiss,
//        title = {
//            Text(
//                text = "删除设备",
//                color = Color.White,
//                fontWeight = FontWeight.Bold
//            )
//        },
//        text = {
//            Text(
//                text = "确定要删除设备" +   deviceName + "吗？此操作不可恢复。",
//                color = Color.White
//            )
//        },
//        confirmButton = {
//            TextButton(onClick = onConfirm) {
//                Text("确定删除", color = Error)
//            }
//        },
//        dismissButton = {
//            TextButton(onClick = onDismiss) {
//                Text("取消", color = Color.White)
//            }
//        },
//        containerColor = CardBackground,
//        titleContentColor = Color.White,
//        textContentColor = Color.White
//    )
}


@Composable
fun SettingDialog(
    functionsConfig:FunctionsConfig,
    viewModel: HomeViewModel,
    enableAuthentication: Boolean,
    useMeijiaCar: Boolean,
    useCarAudio: Boolean,
    showSetting: Boolean,
    onDismissRequest: () -> Unit,
) {

    if (showSetting) {
        Dialog(
            onDismissRequest = onDismissRequest,
            properties = DialogProperties(
                usePlatformDefaultWidth = false
            )

        ) {

            val widthPixels = LocalContext.current.resources.displayMetrics.widthPixels
            val targetDensity = widthPixels / 1060f
            CompositionLocalProvider(LocalDensity provides Density(density = targetDensity)) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth(0.8f)
                        .shadow(8.dp, RoundedCornerShape(12.dp))
                        .background(Color(0xFF3C3C48))
                        .clip(RoundedCornerShape(12.dp))
                ) {
                    Column(
                        modifier = Modifier.padding(8.dp)
                    ) {

                        Text(
                            modifier = Modifier.padding(10.dp),
                            text = "车型选择",
                            color = Color.White,
                            fontSize = 20.sp
                        )
                        CarsTypeGrid(
                            functions = functionsConfig.getCarFunctions(),
                            useMeijiaCar = useMeijiaCar,
                            useCarAudio = useCarAudio,
                            viewModel = viewModel
                        )
                        Spacer(modifier = Modifier.height(30.dp))
                        Text(
                            modifier = Modifier.padding(10.dp),
                            text = "开发者项",
                            color = Color.White,
                            fontSize = 20.sp
                        )
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(12.dp),
                            horizontalArrangement = Arrangement.Start,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Switch(
                                modifier = Modifier.height(10.dp),
                                checked = enableAuthentication,
                                onCheckedChange = { viewModel.toggleAuthentication() }
                            )
                            Spacer(modifier = Modifier.width(10.dp))
                            Text(
                                text = "设备鉴权",
                                style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun SettingDialog2(
    functionsConfig:FunctionsConfig,
    viewModel: HomeViewModel,
    enableAuthentication: Boolean,
    useMusic: String,
    showSetting: Boolean,
    onDismissRequest: () -> Unit,
) {

    if (showSetting) {
        Dialog(
            onDismissRequest = onDismissRequest,
            properties = DialogProperties(
                usePlatformDefaultWidth = false
            )

        ) {

            val widthPixels = LocalContext.current.resources.displayMetrics.widthPixels
            val targetDensity = widthPixels / 1060f
            CompositionLocalProvider(LocalDensity provides Density(density = targetDensity)) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth(0.8f)
                        .shadow(8.dp, RoundedCornerShape(12.dp))
                        .background(Color(0xFF3C3C48))
                        .clip(RoundedCornerShape(12.dp))
                ) {
                    Column(
                        modifier = Modifier.padding(8.dp)
                    ) {

                        Text(
                            modifier = Modifier.padding(10.dp),
                            text = "音效选择",
                            color = Color.White,
                            fontSize = 20.sp
                        )
                        CarsTypeGrid2(
                            functions = functionsConfig.getCarFunctions(),
                            useMusic= useMusic,
                            viewModel = viewModel
                        )
                        Spacer(modifier = Modifier.height(30.dp))
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(12.dp),
                            horizontalArrangement = Arrangement.Start,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Switch(
                                modifier = Modifier.height(10.dp),
                                checked = enableAuthentication,
                                onCheckedChange = { viewModel.toggleMusic() }
                            )
                            Spacer(modifier = Modifier.width(10.dp))
                            Text(
                                text = "音效开关",
                                style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }
                }
            }
        }
    }
}


/**
 * 设置内车型选择网格
 */
@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun CarsTypeGrid(
    functions: List<ButtonFunction>,
    useMeijiaCar: Boolean,
    useCarAudio: Boolean,
    viewModel: HomeViewModel
) {
    LazyVerticalGrid(
        columns = GridCells.Fixed(3),
        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(functions) { function ->
            FunctionCard2(
                name = function.name,
                iconResId = function.iconResId,
                isAppSelector = function.id == "launch_app",
                // 修改选中状态判断逻辑
                isSelected =  when(function.id){
                    "s05" -> useCarAudio
                    "l07" -> useMeijiaCar
                    else ->  false
                },
                onClick = {
                    // 如果是开启应用功能，直接进入应用选择页面
                    viewModel.toSaveChoseCar(function.id)
                    when(function.id){
                        "s05" -> viewModel.toggleCarAudio()
                        "l07" -> viewModel.toggleCarExecutor()
                    }
                }
            )
        }
    }
}

/**
 * 设置内车型选择网格
 */
@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun CarsTypeGrid2(
    functions: List<ButtonFunction>,
    useMusic: String,
    viewModel: HomeViewModel
) {
    LazyVerticalGrid(
        columns = GridCells.Fixed(3),
        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(functions) { function ->
            FunctionCard2(
                name = function.name,
                iconResId = function.iconResId,
                isAppSelector = function.id == "launch_app",
                // 修改选中状态判断逻辑
                isSelected =  function.id==useMusic,
                onClick = {
                    // 如果是开启应用功能，直接进入应用选择页面
                    viewModel.toSaveChoseCar(function.id)

                }
            )
        }
    }
}


/**
 * 功能卡片
 */
@Composable
fun FunctionCard2(
    name: String,
    iconResId: Int?,
    isAppSelector: Boolean,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier.fillMaxWidth()
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(100.dp)
                .clickable(onClick = onClick),
            colors = CardDefaults.cardColors(
                containerColor = if (isSelected)
                    MaterialTheme.colorScheme.primaryContainer
                else
                    MaterialTheme.colorScheme.surface
            ),
            shape = RoundedCornerShape(8.dp),
            elevation = CardDefaults.cardElevation(
                defaultElevation = if (isSelected) 4.dp else 2.dp
            )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(8.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                // 使用通用图标组件
                FunctionIcon(
                    iconResId = iconResId,
                    name = name,
                    category = if (isAppSelector) FunctionCategory.APP else null,
                    size = 64.dp,
                    iconSize = 48.dp,
                    backgroundColor = if (isSelected)
                        MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
                    else
                        MaterialTheme.colorScheme.surfaceVariant,
                    contentColor = if (isSelected)
                        MaterialTheme.colorScheme.primary
                    else
                        MaterialTheme.colorScheme.onSurfaceVariant
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = name,
                    style = MaterialTheme.typography.bodyMedium,
                    color = if (isSelected)
                        MaterialTheme.colorScheme.onPrimaryContainer
                    else
                        MaterialTheme.colorScheme.onSurface,
                    fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                    textAlign = TextAlign.Center
                )
            }
        }

        // 选中状态标志
        if (isSelected) {
            Box(
                modifier = Modifier
                    .padding(top = 8.dp, end = 8.dp)  // 使用 padding 代替 offset
                    .size(16.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primary)
                    .align(Alignment.TopEnd)
            )
        }
    }
}

@Composable
fun DeviceIcon() {
    // 自定义设备图标
    Icon(
        painter = painterResource(id = R.mipmap.logo2),
        contentDescription = "设备",
        tint = Color.Unspecified,
        modifier = Modifier.size(96.dp)
    )
}

@Composable
fun DeviceFunctions(device: Device) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // 显示短按功能
        device.shortPressFunction?.let { function ->
            FunctionItem(function, "tap")
        }

//        // 显示长按功能
//        device.longPressFunction?.let { function ->
//            FunctionItem(function, "long_press")
//        }

        // 显示双击功能
        device.doubleClickFunction?.let { function ->
            FunctionItem(function, "double_click")
        }

        // 显示左旋功能
        device.leftRotateFunction?.let { function ->
            FunctionItem(function, "rotate_left")
        }
    }
}

@Composable
fun FunctionItem(function: ButtonFunction, type: String) {
    Card(
        modifier = Modifier
            .width(112.dp),
        shape = MaterialTheme.shapes.medium // 大圆角
    ) {
        Column(
            modifier = Modifier
                .width(112.dp)
                .background(Color.Transparent)
                .border(1.dp, Color.Transparent, RoundedCornerShape(16.dp)),
        ) {
            Box(
                modifier = Modifier.align(Alignment.CenterHorizontally).padding(8.dp)
            ) {
                val context = LocalContext.current
                val packageManager = context.packageManager
                var appIcon by remember { mutableStateOf<Bitmap?>(null) }
                if (function.category == FunctionCategory.APP) {
                    //加载应用图标
                    val packageName = function.actionCode.substring(4)
                    val icon: Drawable = packageManager.getApplicationIcon(packageName)
                    appIcon = icon.toBitmap(80, 80)
                    Image(
                        bitmap = appIcon!!.asImageBitmap(),
                        contentDescription = function.name,
                        modifier = Modifier.size(80.dp),
                        contentScale = ContentScale.Fit
                    )
                } else if (function.iconResId != 0) {
                    Icon(
                        painter = painterResource(id = function.iconResId),
                        contentDescription = function.name,
                        tint = Color.White,
                        modifier = Modifier.size(80.dp),
                    )
                } else {
                    Icon(
                        painter = painterResource(id = getFunctionIcon(type)),
                        contentDescription = function.name,
                        tint = Color.White,
                        modifier = Modifier.size(80.dp),
                    )
                }
            }

            Text(
                text = "${getFunctionTypeName(type)}: ${function.name}",
                color = Color.White,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth(),
                fontSize = 12.sp,
                maxLines = 1
            )
        }
    }
}

@Composable
fun AddDeviceCard(onAddClick: () -> Unit) {
    Card(
        modifier = Modifier
            .width(160.dp)
            .height(220.dp)
            .clickable(onClick = onAddClick),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = CardBackground
        ),
        border = BorderStroke(1.dp, BorderColor)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Icon(
                painter = painterResource(id = R.drawable.ic_add_device),
                contentDescription = "添加设备",
                tint = Color.White,
                modifier = Modifier.size(64.dp)
            )

            Spacer(modifier = Modifier.height(16.dp))

            Text(
                text = "连接新设备",
                color = Color.White,
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium
            )
        }
    }
}

// 辅助函数
fun getBatteryIcon(level: Int): Int {
    return when {
        level >= 80 -> R.drawable.ic_battery_full
        level >= 50 -> R.drawable.ic_battery_half
        level >= 20 -> R.drawable.ic_battery_low
        else -> R.drawable.ic_battery_empty
    }
}

fun getBatteryColor(level: Int): Color {
    return when {
        level >= 50 -> Success
        level >= 20 -> Warning
        else -> Error
    }
}

fun getFunctionIcon(type: String): Int {
    return when (type) {
        "tap" -> R.drawable.ic_tap
        "long_press" -> R.drawable.ic_long_press
        "double_click" -> R.drawable.ic_double_click
        "rotate_left" -> R.drawable.ic_rotate_left
        "rotate_right" -> R.drawable.ic_rotate_right
        else -> R.drawable.ic_function
    }
}

fun getFunctionTypeName(type: String): String {
    return when (type) {
        "tap" -> "短按"
        "long_press" -> "长按"
        "double_click" -> "双击"
        "rotate_left" -> "旋转"
        "rotate_right" -> "旋转"
        else -> type
    }
}

@Composable
fun TestDialog(
    stringMaessage: String,
    onDismiss: () -> Unit,
    onConfirm: () -> Unit
) {

    Dialog(onDismissRequest = onDismiss) {
        val widthPixels = LocalContext.current.resources.displayMetrics.widthPixels
        val targetDensity = widthPixels / 1060f
        CompositionLocalProvider(LocalDensity provides Density(density = targetDensity)) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = CardBackground
            ) {
                Column(
                    modifier = Modifier
                        .padding(24.dp)
                        .width(300.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "测试梧桐配置字显示值",
                        color = Color.White,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )

                    Spacer(modifier = Modifier.height(16.dp))

                    Text(
                        text = stringMaessage,
                        color = Color.White
                    )

                    Spacer(modifier = Modifier.height(24.dp))

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End
                    ) {

                        TextButton(onClick = onConfirm) {
                            Text("知道了", color = Color.White)
                        }
                    }
                }
            }
        }
    }
}
